package com.hr.feign.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @desc:  微服务之间使用Feign调用接口时, 透传header参数信息
 * @author: cao_wencao
 * @date: 2020-09-25 16:36
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        /**
         * 获取当前线程中的request信息。
         * 如果重新配置熔断器隔离策略，在多线程环境下这种情况是可能取不到原始的request信息的
         */
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //获取所有的原始header
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                //将header设置到 Feign 调用的方的 header中去
                requestTemplate.header(name, values);
            }
        }
    }
}